package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tjvib.R;
import com.tjvib.adapter.OrderAdapter;
import com.tjvib.base.BaseActivity;
import com.tjvib.bean.OrderBean;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.CopyUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.ApiInterface;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.HintDialog;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.AndroidScheduler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class OrderActivity extends BaseActivity {

    private ApiInterface apiInterface = RetrofitHelper.retrofitHelper.create();

    private RecyclerView order_rv;

    private OrderAdapter orderAdapter;
    private List<OrderBean> orderBeanList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_order;
    }

    @Override
    protected boolean initView() {
        order_rv = findViewById(R.id.order_rv);
        order_rv.setLayoutManager(new LinearLayoutManager(this));
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(order_rv);
        return true;
    }

    @Override
    protected boolean initData() {
        orderAdapter = new OrderAdapter(R.layout.item_order, orderBeanList);
        orderAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                showHelpDialog(orderBeanList.get(position));
            }
        });
        order_rv.setAdapter(orderAdapter);

        initOrderList();

        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    private void initOrderList() {
        LoadingDialog loadingDialog = new LoadingDialog(OrderActivity.this);
        loadingDialog.showDialog(this, "正在加载...");
        apiInterface.get_list(String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        if (value.getCode() == SUCCESS) {
                            loadingDialog.dismiss();
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                            updateOrderList(String.valueOf(value.getData()));
                        } else {
                            LogUtil.e("get_list response false");
                            showErrorDialog(value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e("get_list response error");
                        showErrorDialog(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void updateOrderList(String data) {
        try {
            orderBeanList.clear();
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String timestamp = jsonObject.getString("timestamp");
                String product = jsonObject.getString("product");
                double amount = jsonObject.getDouble("amount");
                String result = jsonObject.getString("result");
                int type = jsonObject.getInt("type");
                orderBeanList.add(new OrderBean(product, id, timestamp, "" + amount,
                        result.equals("成功") ? true : false, type));
            }
            Collections.reverse(orderBeanList);
            runOnUiThread(() -> orderAdapter.notifyDataSetChanged());
        } catch (JSONException e) {
            showErrorDialog("解析服务器数据失败");
        }
    }

    private void showHelpDialog(OrderBean order) {
        runOnUiThread(() -> {
            HintDialog hintDialog = new HintDialog(OrderActivity.this);
            hintDialog.setConfirmText("发送");
            hintDialog.showDialog(OrderActivity.this, "反馈",
                    "如果您对此订单有疑问或者需要退款，请联系我们的邮箱tsmartvib@163.com，我们会收到后会尽快回复您。",
                    view -> {
                        sendEmail(order);
                        if (hintDialog.isShowing())
                            hintDialog.dismiss();
                    },
                    view -> {
                        if (hintDialog.isShowing())
                            hintDialog.dismiss();
                    });
        });
    }


    private void sendEmail(OrderBean order) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:"));
        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"tsmartvib@163.com"});
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "订单号" + getString(R.string.email_subject_order));
        intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_text_order,
                UserManager.getInstance().getUserId(), order.getId(), order.getTitle(),
                order.getMoney(), order.isPay() ? "支付成功" : "支付失败"));
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            ToastUtil.show("当前设备似乎没有邮箱app，邮箱地址已复制成功，请您自行发送邮件");
            CopyUtil.getInstance(OrderActivity.this).CopyText("tsmartvib@163.com");
        }
    }

}